using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;

namespace UnitTesting.Fixturing
{
	class RhinoMockActivator : MockActivatorBase
	{
		const string TARGET_TYPE_NAME = "Rhino.Mocks.MockRepository";
		const string TARGET_METHOD_NAME = "GenerateStub";

		internal Type TargetType { get; set; }

		internal RhinoMockActivator(Assembly assembly)
		{
			TargetType = ActivatorManager.GetTargetType(assembly, TARGET_TYPE_NAME);
		}

		protected override object CreateInstance(Type type, object[] arguments)
		{
			var targetMethod = TargetType.GetMethod(TARGET_METHOD_NAME, new[] {typeof (Type), typeof (object[])});
			EnsureIsNotNull(targetMethod);
			return targetMethod.Invoke(null, new object[] {type, arguments});
		}

		[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "GenerateStub")]
		void EnsureIsNotNull(MethodInfo targetMethod)
		{
			if (targetMethod == null)
			{
				throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The type '{0}' doest not contain the method '{1}'.", TargetType, TARGET_METHOD_NAME));
			}
		}
	}
}